package com.qys.livesMall.app.user.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qys.livesMall.app.user.model.dto.sys.UserRewardConfigDTO;
import com.qys.livesMall.app.user.model.dto.sys.UserRewardConfigListDTO;
import com.qys.livesMall.app.user.model.entity.UserRewardConfig;
import com.qys.livesMall.app.user.mapper.UserRewardConfigMapper;
import com.qys.livesMall.app.user.model.vo.sys.UserRewardConfigListVO;
import com.qys.livesMall.app.user.service.UserRewardConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.finance.common.Constant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 主播奖励配置 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-10-31
 */
@Service
public class UserRewardConfigServiceImpl extends ServiceImpl<UserRewardConfigMapper, UserRewardConfig> implements UserRewardConfigService {


    @Override
    public Boolean addAll(UserRewardConfigListDTO dto) {
        baseMapper.deleteAll();
        List<UserRewardConfig> list=new ArrayList<>();
        if (null != dto.getFirstChargeWithdrawal()){
            UserRewardConfig userRewardConfig=new UserRewardConfig();
            userRewardConfig.setAwardType(1);
            userRewardConfig.setAwardUnit(dto.getFirstChargeWithdrawal());
            list.add(userRewardConfig);
        }
        if (null != dto.getNewUserRegistration()){
            UserRewardConfig userRewardConfig=new UserRewardConfig();
            userRewardConfig.setAwardType(2);
            userRewardConfig.setAwardUnit(dto.getNewUserRegistration());
            list.add(userRewardConfig);
        }
        if (null != dto.getNewUserRechargeRewards()){
            UserRewardConfig userRewardConfig=new UserRewardConfig();
            userRewardConfig.setAwardType(4);
            userRewardConfig.setAwardUnit(dto.getNewUserRechargeRewards());
            list.add(userRewardConfig);
        }
        if (null != dto.getNewRegisterIP()){
            UserRewardConfig userRewardConfig=new UserRewardConfig();
            userRewardConfig.setAwardType(6);
            userRewardConfig.setAwardUnit(dto.getNewRegisterIP());
            list.add(userRewardConfig);
        }
        if (null != dto.getRechargeRewards()){
            list.addAll(dto.getRechargeRewards());
        }
        if (null != dto.getWithdrawalFee()){
            list.addAll(dto.getWithdrawalFee());
        }
        if (null != dto.getWhiteListIp()){
            list.addAll(dto.getWhiteListIp());
        }
        if (null != dto.getUpgradeRewards()){
            list.addAll(dto.getUpgradeRewards());
        }
        if (null != dto.getSendOutRewards()){
            list.addAll(dto.getSendOutRewards());
        }
        return saveBatch(list);
    }

    @Override
    public UserRewardConfigListVO selectAll() {
        List<UserRewardConfig> list=list();
        UserRewardConfigListVO userRewardConfigListVO=new UserRewardConfigListVO();
        if (CollectionUtil.isNotEmpty(list)){
            //1首充提现需要完成线下理财数量
            List<BigDecimal> firstChargeWithdrawals =list.stream().filter(a->a.getAwardType()==1).map(UserRewardConfig::getAwardUnit).collect(Collectors.toList());
            userRewardConfigListVO.setFirstChargeWithdrawal(CollectionUtil.isNotEmpty(firstChargeWithdrawals)?firstChargeWithdrawals.get(0):null);
            //2新用户注册奖励
            List<BigDecimal> newUserRegistrations =list.stream().filter(a->a.getAwardType()==2).map(UserRewardConfig::getAwardUnit).collect(Collectors.toList());
            userRewardConfigListVO.setNewUserRegistration(CollectionUtil.isNotEmpty(newUserRegistrations)?newUserRegistrations.get(0):null);
            //4 首充返现
            List<BigDecimal> newUserRechargeRewards =list.stream().filter(a->a.getAwardType()==4).map(UserRewardConfig::getAwardUnit).collect(Collectors.toList());
            userRewardConfigListVO.setNewUserRechargeRewards(CollectionUtil.isNotEmpty(newUserRechargeRewards)?newUserRechargeRewards.get(0):null);
            //6同IP注册数量限制
            List<BigDecimal> newRegisterIPs =list.stream().filter(a->a.getAwardType()==6).map(UserRewardConfig::getAwardUnit).collect(Collectors.toList());
            userRewardConfigListVO.setNewRegisterIP(CollectionUtil.isNotEmpty(newRegisterIPs)?newRegisterIPs.get(0):null);
            //6同IP注册数量限制
            List<BigDecimal> effectiveUser =list.stream().filter(a->a.getAwardType()==10).map(UserRewardConfig::getAwardUnit).collect(Collectors.toList());
            userRewardConfigListVO.setEffectiveUser(CollectionUtil.isNotEmpty(effectiveUser)?effectiveUser.get(0):null);
            //3充值返现
            List<UserRewardConfig> rechargeRewards=list.stream().filter(a->a.getAwardType()==3).collect(Collectors.toList());
            userRewardConfigListVO.setRechargeRewards(rechargeRewards);
            //5个人提现手续费
            List<UserRewardConfig> withdrawalFees=list.stream().filter(a->a.getAwardType()==5).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(withdrawalFees) && withdrawalFees.size()>1){
                userRewardConfigListVO.setWithdrawalFee(withdrawalFees);
            }else if (CollectionUtil.isNotEmpty(withdrawalFees) && withdrawalFees.size() == 1){
                UserRewardConfig userRewardConfig=new UserRewardConfig();
                userRewardConfig.setAwardUnit(BigDecimal.ZERO);
                userRewardConfig.setAwardType(5);
                if (userRewardConfig.getAwardUnit().toString().equals(Constant.PayMethod.USDT)){
                    userRewardConfig.setAwardCondition(Constant.PayMethod.BANK_CARD);
                }else {
                    userRewardConfig.setAwardCondition(Constant.PayMethod.USDT);
                }
                withdrawalFees.add(userRewardConfig);
                userRewardConfigListVO.setWithdrawalFee(withdrawalFees);
            }else {
                UserRewardConfig userRewardConfig=new UserRewardConfig();
                userRewardConfig.setAwardUnit(BigDecimal.ZERO);
                userRewardConfig.setAwardType(5);
                userRewardConfig.setAwardCondition(Constant.PayMethod.USDT);

                UserRewardConfig userRewardConfig1=new UserRewardConfig();
                userRewardConfig1.setAwardUnit(BigDecimal.ZERO);
                userRewardConfig1.setAwardType(5);
                userRewardConfig1.setAwardCondition(Constant.PayMethod.BANK_CARD);
                withdrawalFees=new ArrayList<>();
                withdrawalFees.add(userRewardConfig);
                withdrawalFees.add(userRewardConfig1);
                userRewardConfigListVO.setWithdrawalFee(withdrawalFees);
            }

            //7IP白名单
            List<UserRewardConfig> whiteListIps=list.stream().filter(a->a.getAwardType()==7).collect(Collectors.toList());
            userRewardConfigListVO.setWhiteListIp(whiteListIps);
            //8升级奖励
            List<UserRewardConfig> upgradeRewards=list.stream().filter(a->a.getAwardType()==8).collect(Collectors.toList());
            userRewardConfigListVO.setUpgradeRewards(CollectionUtil.isNotEmpty(upgradeRewards)?upgradeRewards.get(0).getAwardUnit():null);
            //9送出奖励
            List<UserRewardConfig> sendOutRewards=list.stream().filter(a->a.getAwardType()==9).collect(Collectors.toList());
            userRewardConfigListVO.setSendOutRewards(sendOutRewards);
        }
        return userRewardConfigListVO;
    }

    @Override
    public Boolean updateType(UserRewardConfigDTO dto) {
        LambdaQueryWrapper<UserRewardConfig> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRewardConfig::getAwardType,dto.getAwardType());
        UserRewardConfig userRewardConfig=baseMapper.selectOne(queryWrapper);
        if (null != userRewardConfig){
            userRewardConfig.setAwardUnit(dto.getAwardUnit());
            baseMapper.updateById(userRewardConfig);
        }else {
            userRewardConfig=new UserRewardConfig();
            userRewardConfig.setAwardType(1);
            userRewardConfig.setAwardUnit(dto.getAwardUnit());
            save(userRewardConfig);
        }
        return true;
    }

    @Override
    public Boolean add(UserRewardConfig dto) {
        if (dto.getAwardType()==3){
            if (StringUtils.isNotBlank(dto.getAwardAmount()) || dto.getAwardAmount().equals("0")){
                if (dto.getAwardUnit().compareTo(new BigDecimal(100))>0){
                    throw new QysException(MessageUtils.message("proportion.ge.hundred"));
                }
            }
            LambdaQueryWrapper<UserRewardConfig> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(UserRewardConfig::getAwardType,3);
            queryWrapper.ne(null !=dto.getConId(),UserRewardConfig::getConId,dto.getConId());
            List<UserRewardConfig> userRewardConfigs=list(queryWrapper);
            if (CollectionUtil.isNotEmpty(userRewardConfigs)){
                JSONObject json= JSONUtil.parseObj(dto.getAwardCondition());
                Double newMinPoint= Double.valueOf(json.get("minPoint").toString());
                Double newMaxPoint= Double.valueOf(json.get("maxPoint").toString());
                for (UserRewardConfig userRewardConfig:userRewardConfigs) {
                    JSONObject oldJson= JSONUtil.parseObj(userRewardConfig.getAwardCondition());
                    Double oldMinPoint= Double.valueOf(oldJson.get("minPoint").toString());
                    Double oldMaxPoint= Double.valueOf(oldJson.get("maxPoint").toString());
                    if (isOverlap(newMinPoint,newMaxPoint,oldMinPoint,oldMaxPoint)){
                        throw new QysException(MessageUtils.message("point.is.exist"));
                    }
                }
            }
        }
        if (dto.getAwardType()==4 || dto.getAwardType()==8){
            if (dto.getAwardUnit().compareTo(new BigDecimal(100))>0){
                throw new QysException(MessageUtils.message("proportion.ge.hundred"));
            }
        }
        return saveOrUpdate(dto);
    }

    public static Boolean isOverlap(Double newMinPoint, Double newMaxPoint, Double oldMinPoint, Double oldMaxPoint){
        return Math.max(newMinPoint, oldMinPoint) < Math.min(newMaxPoint, oldMaxPoint);
    }
}
